package com.ee.chat.cps.admin.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.ee.chat.common.bean.Result;
import com.ee.chat.common.dao.ChannelMapper;
import com.ee.chat.common.entity.Channel;
import com.ee.chat.cps.admin.service.IChannelOperationService;
import com.ee.chat.cps.admin.service.ILoginService;
import com.ndhutu.ee.util.MD5Util;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

@Service
public class LoginServiceImpl implements ILoginService {
    @Resource
    ChannelMapper channelMapper;
    @Resource
    IChannelOperationService operationService;

    @Override
    public Result login(HttpServletRequest request, String username, String password) throws Exception {
        HttpSession session = request.getSession(true);

        QueryWrapper<Channel> wrapper = new QueryWrapper<>();
        wrapper.eq("username", username);
        Channel channelUser = channelMapper.selectOne(wrapper);
        if(channelUser == null || !MD5Util.encode32(password).equals(channelUser.getPassword())){
            return Result.returnFailure("用户名密码错误");
        }
        if(channelUser.getStatus() != 0){
            return Result.returnFailure("账号已禁用");
        }

        session.setAttribute("channelUser", channelUser);

        operationService.addOperationLog(request, "登录成功");

        return Result.returnSuccess(null);
    }

    @Override
    public Result updPwd(HttpServletRequest request, String oldPwd, String newPwd) throws Exception {
        HttpSession session = request.getSession(true);
        Channel channelUser = (Channel) session.getAttribute("channelUser");

        if(!channelUser.getPassword().equals(MD5Util.encode32(oldPwd))){
            return Result.returnFailure("原密码错误，请重新填写");
        }

        channelUser.setPassword(MD5Util.encode32(newPwd));
        channelMapper.updateById(channelUser);
        session.setAttribute("channelUser", channelUser);

        operationService.addOperationLog(request, "更新密码");

        return Result.returnSuccess(null);
    }
}
